/*
 * Copyright (c) 2010, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/core/Memory.h"
#include "alkes/codec/PngUtil.h"


#if ALKES_API_WIN32
#if defined(ALKES_DEBUG)
#pragma comment(lib, "libpngd.lib")
#pragma comment(lib, "zlibd.lib")
#else
#pragma comment(lib, "libpng.lib")
#pragma comment(lib, "zlib.lib")
#endif
#endif

#define CHECK_SIG_SIZE  (8)

struct PngReaderImpl
{
    png_structp png_ptr;
    png_infop info_ptr;
    void* opaque;
    read_png_callback read_data_fn;
    uint16_t width;
    uint16_t height;
};

enum RetCode
{
    PNG_ERR_SUCCESS = 0,
    PNG_ERR_NO_PNG_IMAGE,
    PNG_ERR_IN_LIBPNG,
    PNG_ERR_SHORT_OF_MEMORY,
    PNG_ERR_NULL_READER,
    PNG_ERR_INVALID_ARGS,
    PNG_ERR_SHORT_OF_ROWBYTES,
    PNG_ERR_HUGE_IMAGE,
};

static void local_read_data_fn(png_structp png_ptr, png_bytep data, png_size_t length);

extern int alkes_create_png_reader(void* opaque, read_png_callback read_data_fn, PngReader* out_reader)
{
    struct PngReaderImpl* reader;
    int ret = PNG_ERR_IN_LIBPNG;
    int update = 0;

    if (!read_data_fn || !out_reader)
        return PNG_ERR_INVALID_ARGS;

    // Check signature
    {
        uint8_t signature[CHECK_SIG_SIZE];
        read_data_fn(opaque, signature, CHECK_SIG_SIZE);
        if (0 != png_sig_cmp(signature, 0, CHECK_SIG_SIZE))
            return PNG_ERR_NO_PNG_IMAGE;
    }

    reader = (struct PngReaderImpl*)alkes_malloc(sizeof(struct PngReaderImpl));

    if (!reader)
        return PNG_ERR_SHORT_OF_MEMORY;

    memset(reader, 0, sizeof(struct PngReaderImpl));

    reader->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (!reader->png_ptr)
        goto error_occured;

    reader->info_ptr = png_create_info_struct(reader->png_ptr);
    if (!reader->info_ptr)
        goto error_occured;

    if (setjmp(png_jmpbuf(reader->png_ptr)))
        goto error_occured;

    reader->opaque = opaque;
    reader->read_data_fn = read_data_fn;

    png_set_read_fn(reader->png_ptr, reader, local_read_data_fn);
    png_set_sig_bytes(reader->png_ptr, CHECK_SIG_SIZE);
    png_read_info(reader->png_ptr, reader->info_ptr);

    {
        png_uint_32 width = png_get_image_width(reader->png_ptr, reader->info_ptr);
        png_uint_32 height = png_get_image_height(reader->png_ptr, reader->info_ptr);

        if (0x7fff < width || 0x7fff < height)
        {
            ret = PNG_ERR_HUGE_IMAGE;
            goto error_occured;
        }

        reader->width = (uint16_t)width;
        reader->height = (uint16_t)height;
    }

    switch (png_get_color_type(reader->png_ptr, reader->info_ptr))
    {
    case PNG_COLOR_TYPE_PALETTE:
        png_set_palette_to_rgb(reader->png_ptr);
        update = 1;
        break;
    case PNG_COLOR_TYPE_GRAY:
        if (png_get_bit_depth(reader->png_ptr, reader->info_ptr) < 8)
        {
            png_set_expand(reader->png_ptr);
            update = 1;
        }
        break;
    default:
        break;
    }

    if (png_get_valid(reader->png_ptr, reader->info_ptr, PNG_INFO_tRNS))
    {
        png_set_tRNS_to_alpha(reader->png_ptr);
        update = 1;
    }

    if (update)
    {
        png_read_update_info(reader->png_ptr, reader->info_ptr);
    }

    *out_reader = reader;
    return PNG_ERR_SUCCESS;

error_occured:
    {
        png_infopp info_ptr = reader->info_ptr ? &reader->info_ptr : NULL;

        png_destroy_read_struct(&reader->png_ptr, info_ptr, NULL);

        alkes_free(reader);
    }

    return ret;
}

extern void alkes_destroy_png_reader(PngReader reader)
{
    struct PngReaderImpl* impl = (struct PngReaderImpl*)reader;

    png_destroy_read_struct(&impl->png_ptr, &impl->info_ptr, NULL);

    alkes_free(impl);
}

extern int alkes_get_png_info(
    PngReader reader,
    uint16_t* width, uint16_t* height,
    int32_t* bit_depth, int32_t* color_type, uint8_t* channels)
{
    struct PngReaderImpl* impl = (struct PngReaderImpl*)reader;

    if (!impl)
        return PNG_ERR_NULL_READER;

    if (width)
        *width = impl->width;

    if (height)
        *height = impl->height;

    if (setjmp(png_jmpbuf(impl->png_ptr)))
        return PNG_ERR_IN_LIBPNG;

    if (bit_depth)
    {
        *bit_depth = png_get_bit_depth(impl->png_ptr, impl->info_ptr);
    }

    if (color_type)
    {
        *color_type = png_get_color_type(impl->png_ptr, impl->info_ptr);
    }

    if (channels)
    {
        *channels = png_get_channels(impl->png_ptr, impl->info_ptr);
    }

    return PNG_ERR_SUCCESS;
}

extern int alkes_set_png_trans(PngReader reader, uint32_t trans)
{
    struct PngReaderImpl* impl = (struct PngReaderImpl*)reader;

    if (!impl)
        return PNG_ERR_NULL_READER;

    if (0 == trans)
        return PNG_ERR_SUCCESS;

    if (setjmp(png_jmpbuf(impl->png_ptr)))
        return PNG_ERR_IN_LIBPNG;

    if (trans & AL_PNGTRANS_STRIP_16)
    {
        png_set_strip_16(impl->png_ptr);
    }

    if (trans & AL_PNGTRANS_PACKING)
    {
        png_set_packing(impl->png_ptr);
    }

    if (trans & AL_PNGTRANS_BGR)
    {
        png_set_bgr(impl->png_ptr);
    }

    if (trans & AL_PNGTRANS_SWAP_ALPHA)
    {
        png_set_swap_alpha(impl->png_ptr);
    }

    if (trans & AL_PNGTRANS_STRIP_ALPHA)
    {
        png_set_strip_alpha(impl->png_ptr);
    }

    if (trans & AL_PNGTRANS_ADD_ALPHA)
    {
        png_set_add_alpha(impl->png_ptr, 0xff, PNG_FILLER_AFTER);
    }

    // update info.
    if (trans & 0xffff)
    {
        png_read_update_info(impl->png_ptr, impl->info_ptr);
    }

    return PNG_ERR_SUCCESS;
}

extern int alkes_decode_png(
    PngReader reader,
    void* buffer, int32_t pitch, uint16_t height, uint32_t trans)
{
    int ret;
    png_size_t rowbytes;
    struct PngReaderImpl* impl = (struct PngReaderImpl*)reader;
    uint8_t* ptr = (uint8_t*)buffer;

    if (!impl)
        return PNG_ERR_NULL_READER;

    if (!buffer || pitch == 0 || impl->height < height)
        return PNG_ERR_INVALID_ARGS;

    ret = alkes_set_png_trans(reader, trans);
    if (0 != ret)
        return ret;

    if (setjmp(png_jmpbuf(impl->png_ptr)))
        return PNG_ERR_IN_LIBPNG;

    rowbytes = png_get_rowbytes(impl->png_ptr, impl->info_ptr);
    if ((png_size_t)abs(pitch) < rowbytes)
        return PNG_ERR_SHORT_OF_ROWBYTES;

    {
        uint16_t i;
        for (i = 0; i < height; ++i, ptr += pitch)
        {
            png_read_row(impl->png_ptr, ptr, NULL);
        }
    }

    return PNG_ERR_SUCCESS;
}

static void local_read_data_fn(png_structp png_ptr, png_bytep data, png_size_t length)
{
    struct PngReaderImpl* impl = (struct PngReaderImpl*)png_get_io_ptr(png_ptr);

    impl->read_data_fn(impl->opaque, data, length);
}
